package krx;

import java.awt.geom.Point2D;

import robocode.util.Utils;

public class WaveBullet
{
	private double startX, startY, startBearing, power;
	private long   fireTime;
	private double    direction;
	private double[]  returnSegment;
	
	public WaveBullet(double x, double y, double bearing, double power, double direction, long time, double[] segment)
	{
		startX         = x;
		startY         = y;
		startBearing   = bearing;
		this.power     = power;
		this.direction = direction;
		fireTime       = time;
		returnSegment  = segment;
	}
	
	public double getBulletSpeed()
	{
		return 20 - power * 3;
	}
	
	public double maxEscapeAngle()
	{
		return Math.asin(8 / getBulletSpeed());
	}

	public static double rollingAvg(double value, double newEntry, double n, double weighting ) {
	    return (value * n + newEntry * weighting)/(n + weighting);
	} 

	static int readings = 0;

	public boolean checkHit(double enemyX, double enemyY, long currentTime)
	{
		//if the distance from the wave origin to our enemy has passed the distance the bullet would have traveled...
		if (Point2D.distance(startX, startY, enemyX, enemyY) <= (currentTime-fireTime)*getBulletSpeed())
		{
			double desiredDirection = Math.atan2(enemyX-startX, enemyY-startY);
			double angleOffset = Utils.normalRelativeAngle(desiredDirection-startBearing);
			double guessFactor = Math.max(-1, Math.min(1, angleOffset/maxEscapeAngle()))*direction;
			int index = (int)Math.round((returnSegment.length-1)/2*(guessFactor+1));
			returnSegment[index] = rollingAvg(returnSegment[index], 1, Math.min(readings++, 200), 1);
			for (int i = 0; i < returnSegment.length; i++)
				if (i != index)
					returnSegment[index] = rollingAvg(returnSegment[index], 0, Math.min(readings++, 200), 1);
			return true;
		}
		return false;
	}
}// end WaveBullet class